const mysql = require('mysql');
// console.log(mysql);



var { createConnection } = mysql;

let host = "localhost",
    user = "root",
    password = "root",
    database = "2111";

function createConn(option = {
    host: "localhost",
    user: "root",
    password: "root",
    database: "2111",
}) {
    var conn = createConnection(option);
    conn.connect();
    return conn;
}

// console.log(conn);

// conn.connect();
// 执行sql语句
function search(sql, option) {
    return new Promise(function (resolve, reject) {
        let conn = createConn(option);
        conn.query(sql, function (err, list) {
            if (err) reject(err);
            resolve(list);
        })
        conn.end();
    })
}

function count(sql, option) {
    return new Promise(function (resolve, reject) {
        let conn = createConn(option);
        conn.query(sql, function (err, list) {
            if (err) {
                reject(err)
            } else {
                resolve(list.length);
            }
        })
        conn.end();
    })
}


function searchOne(sql, option) {
    return new Promise(function (resolve, reject) {
        let conn = createConn(option);
        conn.query(sql, function (err, list) {
            if (err) {
                reject(err)
            } else {
                resolve(list[0]);
            }
        })
        conn.end();
    })
}
function searchMany(sql, option) {
    return new Promise(function (resolve, reject) {
        let conn = createConn(option);
        conn.query(sql, function (err, list) {
            if (err) reject(err);
            resolve(list);
        })
        conn.end();
    })
}

function insert(sql, option) {
    return new Promise(function (resolve, reject) {
        let conn = createConn(option);
        conn.query(sql, function (err, info) {
            if (err) reject(err);
            resolve(info);
        })
        conn.end();
    })
}
function del(sql, option) {
    return new Promise(function (resolve, reject) {
        let conn = createConn(option);
        conn.query(sql, function (err, info) {
            if (err) reject(err);
            resolve(info);
        })
        conn.end();
    })
}
function update(sql, option) {
    return new Promise(function (resolve, reject) {
        let conn = createConn(option);
        conn.query(sql, function (err, info) {
            if (err) reject(err);
            resolve(info);
        })
        conn.end();
    })
}


// search("select * forsm `grade`").then(list => {
//     console.log(list);
// }).catch(err => {
//     console.log(err);
// })

module.exports = {
    search,
    searchOne,
    searchMany,
    count,
    insert,
    del,
    update,
}






// conn.end();


